package com.cinyi.ormlite.web.dcp;

import java.io.IOException;
import java.sql.Connection;
import java.util.Map;

import com.cinyi.ormlite.IConfiguration;

public class DbConnectionManager {
	public static final String DEFAULT_SCHEMA = "default" ;
	
	private static DbConnectionManager instance = null;

	private String[] poolNames = null;
	private Map<String, IConnectionProvider> poolMap = new java.util.concurrent.ConcurrentHashMap<String, IConnectionProvider>();
    private boolean initable = false ;
    
    private IConfiguration config ;
    
	private DbConnectionManager(){}
	
	public static DbConnectionManager getInstance() {
		if(instance == null ){
			instance = new DbConnectionManager();
		}
		
		return instance;
	}

	/**
	 * 初始化各种数据库连接池
	 */
	public void start(IConfiguration config) {
        if(initable){
            return ;
        }
        this.config = config ;
        IConnectionProvider broker = createConnectionPool(IConnectionProvider.CP_DRUID,"");
		if(broker != null){
			broker.onStart();
			poolMap.put(DEFAULT_SCHEMA, broker);
		}else{
			throw new RuntimeException("the default database error.");
		}
		
		String dbp = config.get("dbp.alias");
		String type = config.get("dbp.type");
		if (!isBlank(dbp) ) {
			poolNames = dbp.split(",");
			for (String pName : poolNames) {
				IConnectionProvider broker1 = createConnectionPool(type,pName+".");
				if(broker1!=null){
					broker1.onStart();
					poolMap.put(pName, broker1);
				}
			}

		}
		
        initable = true ;
	}
	
	private boolean isBlank(String dbp) {
		return dbp == null || "".equals(dbp.toString().trim());
	}

	/**
	 * 关闭数据源
	 */
	public synchronized void destroy(){
		if(poolNames == null)
			return ;
		
		for (String pName : poolNames) {
			IConnectionProvider provider = poolMap.get(pName);
			if(provider != null)
				provider.onDestroy();
		}
	}

	private IConnectionProvider createConnectionPool(String type,String pName) {
		String className = pName + "driverClassName";
		String validationQuery = pName + "validationQuery";
		String jdbc_url = pName + "jdbc_url";
		String jdbc_username = pName + "jdbc_username";
		String jdbc_password = pName + "jdbc_password";
		String min = pName + "min.con";
		String max = pName + "max.con";
		
		IConnectionProvider broker = null ;
		
		try {
			if(IConnectionProvider.CP_DRUID.equals(type)){
				broker = new DruidConnectionBroker( 
						getString(className), getString(jdbc_url), getString(jdbc_username),
						getString(jdbc_password), getInt(min,2), getInt(max,7),0L);
			}else{
				broker = new DbConnectionBroker(
						getString(className),
						getString(jdbc_url), getString(jdbc_username),
						getString(jdbc_password), getInt(min,2), getInt(max,7), null,
						1.0);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return broker;
	}
	
	private Integer getInt(String name,int def){
		try{
		return Integer.parseInt(name,def);
		}catch(NumberFormatException ne){
			return def ;
		}
	}

	private String getString(String name){
		return config.get(name);
	}
	
	public synchronized Connection getConnection(String name){
		IConnectionProvider pool = poolMap.get(name);
		if(pool != null ){
			return pool.getConnection();
		}
		
		return null ;
	}

}
